Cube.define('Cube.data.HttpRequest', {
	implements: 'Cube.util.Observable',
	
	/**
	 * Create new XMLHttpRequest
	 * 
	 * @param {String} url
	 * @param {String} type
	 * @param {Boolean} async
	 */
	create: function(url, type, async, cache) {
		var self = this;
		
		if (typeof type === 'undefined') type = 'GET';
		if (typeof async === 'undefined') async = true;
		
		if (!cache)
		{
			url += '?_' + new Date().getTime();
		}

		var xhr = this.getXhrInstance();		
		xhr.open(type, url, async);
		
		if (!cache)
		{
			xhr.setRequestHeader("Cache-Control", "no-cache");
			xhr.setRequestHeader("Pragma", "no-cache");
		}
		
		this.fireEvent('beforeSend', xhr);
		
		xhr.send(null);
		
		// For synchronous calls only
		if (async === false)
		{
			self.onReadyStateChange(xhr);
		}
		else if (async === true)
		{
			xhr.onreadystatechange = function() {
				self.onReadyStateChange(xhr);
			};
		}
	},
	
	/**
	 * On Ready State Change async event
	 * 
	 * @private 
	 */
	onReadyStateChange: function(xhr) {
		if (xhr.readyState === 4 && xhr.status === 200)
		{
			this.fireEvent('requestsuccess', xhr.responseText, xhr);
		}
	},
	
	/**
	 * Get XMLHttpRequest instance 
	 */
	getXhrInstance: function() {
        var options = [function() {
            return new XMLHttpRequest();
        }, function() {
            return new ActiveXObject('MSXML2.XMLHTTP.3.0');
        }, function() {
            return new ActiveXObject('MSXML2.XMLHTTP');
        }, function() {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }], i = 0,
            len = options.length,
            xhr;

        for (; i < len; ++i) 
        {
            try 
            {
                xhr = options[i];
                xhr();
                break;
            } 
            catch(e) {}
        }
        return new xhr;
    }
});
